//
//  YH_RegisterViewController.m
//  YinHang
//
//  Created by 123 on 14-6-18.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_RegisterViewController.h"
//#import "YH_WebStyleViewController.h"
#import "YH_HomeViewController.h"

@interface YH_RegisterViewController ()
{
    UIImage *input_normalImg;
    UIImage *input_onImg;
    
    
    ASIFormDataRequest *provinceRequest;//城市(省份)
    ASIFormDataRequest *cityRequest;//频道
    ASIFormDataRequest *userTypeRequest;//会员类型
    
    ASIFormDataRequest *registerRequest;//会员注册
    
    
    NSArray *provinceData;//省份data
    NSString *pid;//省份id
    NSMutableArray *provinceArr;//省份名称数组
    
    NSArray *cityData;//频道data
    NSString *cid;//频道id
    NSMutableArray *cityArr;//频道名称数组
    
    NSArray *userTypeData;//会员类型data
    NSString *mid;//会员类型id
    NSMutableArray *userTypeArr;//会员类型名称数组
    
    MBProgressHUD *loadHud;
}
@end

@implementation YH_RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"注册";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    
    [self setUI];
        
    
    // 初始化数组
    provinceArr = [NSMutableArray array];//省份名称数组
    cityArr = [NSMutableArray array];//频道名称数组
    userTypeArr = [NSMutableArray array];//会员类型名称数组
}

- (void)setUI {
    NSArray *txtFieldArr = @[_chooseArea_cityTxtField,_chooseArea_countyTxtField,_memberTypeTxtField,_usernameTxtField,_pwdTxtField,_confirmPwdTxtField,_emailTxtField,_captchaTxtField];
    input_normalImg = [UIImage imageNamed:@"input_normal"];
    input_onImg = [UIImage imageNamed:@"input_on"];
    for (UITextFieldPadding *txtField in txtFieldArr) {
        // 设置背景
        [txtField setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
        // 设置文本颜色
        txtField.textColor = TEXT_COLOR;
        // 设置文本偏移
        [txtField setPadding:YES top:0 right:2 bottom:0 left:2];
    }
    
    UIImage *postBtn_bgImg = [UIImage imageNamed:@"register_loginbtn"];
    [_postBtn setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [textField setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == _confirmPwdTxtField && ![NSString emptyValidate:_pwdTxtField.text]) {
        if (![_confirmPwdTxtField.text isEqualToString:_pwdTxtField.text]) {
            [SVProgressHUD showErrorWithStatus:@"和所填密码不符 请再次确认！"];
        }
    }
    
    [textField setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
}

// 检测邮箱
- (BOOL)emailCheck:(NSString *)_text{
    NSString *Regex=@"[A-Z0-9a-z._%+-]+@[A-Z0-9a-z._]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
    return [emailTest evaluateWithObject:_text];
    
}

// 密码输入限制（数字字母下划线） <12位
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _pwdTxtField) {
        // return NO to not change text
        if(strlen([textField.text UTF8String]) >= 10 && range.length != 1)
            return NO;
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // 密码输入限制（数字字母下划线） >6位
    if (textField == _pwdTxtField && ![NSString emptyValidate:_emailTxtField.text]) {
        // return NO to not change text
        if(strlen([textField.text UTF8String]) <6)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wrong password" message:@"Password can not less than 6 character" delegate:self cancelButtonTitle:@"Go on Input" otherButtonTitles:nil];
            [alert show];
            return NO;
        }
    }
    
    if (textField == _confirmPwdTxtField && ![NSString emptyValidate:_pwdTxtField.text]) {
        if (![_confirmPwdTxtField.text isEqualToString:_pwdTxtField.text]) {
            [SVProgressHUD showErrorWithStatus:@"和所填密码不符 请再次确认！"];
        }
    }
    
    // 检测邮箱是否有效
    if (textField == _emailTxtField && ![NSString emptyValidate:_emailTxtField.text]) {
        
        if (![self emailCheck:_emailTxtField.text]) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid mail" message:@"请输入有效的邮箱！" delegate:self cancelButtonTitle:@"Go on Input" otherButtonTitles:nil];
            [alert show];
            
            [_emailTxtField becomeFirstResponder];
            
            return NO;
        }
    }
    
    [self allEditActionsResignFirstResponder];
    return YES;
}


#pragma mark - touchMethod
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    
    [self allEditActionsResignFirstResponder];
    
//    [provinceRequest cancel];
//    [cityRequest cancel];
//    [userTypeRequest cancel];
//    [registerRequest cancel];
}

#pragma mark - PrivateMethod
- (void)allEditActionsResignFirstResponder{
    
    // 密码输入限制（数字字母下划线） >6位
    if (![NSString emptyValidate:_pwdTxtField.text]) {
        // return NO to not change text
        if(strlen([_pwdTxtField.text UTF8String]) <6)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wrong password" message:@"Password can not less than 6 character" delegate:self cancelButtonTitle:@"Go on Input" otherButtonTitles:nil];
            [alert show];
            
            [_pwdTxtField becomeFirstResponder];
            
            return ;
        }
    }
    
    if (![NSString emptyValidate:_emailTxtField.text]) {
        // 检测邮箱是否有效
        if (![self emailCheck:_emailTxtField.text]) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid mail" message:@"请输入有效的邮箱！" delegate:self cancelButtonTitle:@"Go on Input" otherButtonTitles:nil];
            [alert show];
            
            [_emailTxtField becomeFirstResponder];
            
            return ;
        }
    }
    
    [_chooseArea_cityTxtField resignFirstResponder];
    [_chooseArea_countyTxtField resignFirstResponder];
    [_memberTypeTxtField resignFirstResponder];
    [_usernameTxtField resignFirstResponder];
    [_pwdTxtField resignFirstResponder];
    [_confirmPwdTxtField resignFirstResponder];
    [_emailTxtField resignFirstResponder];
    [_captchaTxtField resignFirstResponder];
}


// 弹出选择视图（发起请求 请求成功 再去弹出视图）
- (IBAction)showSelectView:(id)sender {
    // 收回键盘
    [self allEditActionsResignFirstResponder];
    
    UIButton *btn = (UIButton*)sender;
    
    /* 请求相应的选择数据 */
    switch (btn.tag) {
        case 1:{//城市
            
            // 检查网络
            if (![Constants isExistenceNetwork]) {
                
            } else {
                // 提示正在加载数据
                loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                loadHud.labelText = @"正在加载数据，请稍后...";
                
                /* 获取全部省份 */
                provinceRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
                provinceRequest.requestMethod = @"POST";
                // 设置超时时间
                provinceRequest.timeOutSeconds = 30;
                provinceRequest.delegate = self;
                // 设置参数
                NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"getallprovince",@""];
                
                NSData *paramsData = [result toGBKEncodingData];
                provinceRequest.postBody = [paramsData mutableCopy];
                
                [provinceRequest startAsynchronous];
            }
        }
            
            break;
            
        case 2:{//频道
            // 如果没有选择城市
            if ([NSString emptyValidate:_chooseArea_cityTxtField.text]) {
                
                [SVProgressHUD showErrorWithStatus:@"请选择城市！"];
                
            } else {
                // 检查网络
                if (![Constants isExistenceNetwork]) {
                    
                } else {
                    // 提示正在加载数据
                    loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                    loadHud.labelText = @"正在加载数据，请稍后...";
                    
                    /* 获取频道 */
                    cityRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
                    cityRequest.requestMethod = @"POST";
                    // 设置超时时间
                    cityRequest.timeOutSeconds = 30;
                    cityRequest.delegate = self;
                    // 设置参数
                    NSDictionary *paramsDict =  @{@"pid": pid};
                    NSString *paramsStr = [NSString JSONString:paramsDict];
                    NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"getcity",paramsStr];
                    
                    NSData *paramsData = [result toGBKEncodingData];
                    cityRequest.postBody = [paramsData mutableCopy];
                    
                    [cityRequest startAsynchronous];
                }
            }
        }
            
            break;
            
        case 3:{//会员类型
            
            // 如果没有选择城市
            if ([NSString emptyValidate:_chooseArea_cityTxtField.text]) {
                
                [SVProgressHUD showErrorWithStatus:@"请选择城市！"];
                
            } else {
                // 如果没有选择频道
                if ([NSString emptyValidate:_chooseArea_countyTxtField.text]) {
                    
                    [SVProgressHUD showErrorWithStatus:@"请选择频道！"];
                    
                } else {
                    
                    // 检查网络
                    if (![Constants isExistenceNetwork]) {
                        
                    } else {
                        // 提示正在加载数据
                        loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                        loadHud.labelText = @"正在加载数据，请稍后...";
                        
                        /* 获取会员类型 */
                        userTypeRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
                        userTypeRequest.requestMethod = @"POST";
                        // 设置超时时间
                        userTypeRequest.timeOutSeconds = 30;
                        userTypeRequest.delegate = self;
                        // 设置参数
                        NSDictionary *paramsDict =  @{@"cid": cid};
                        NSString *paramsStr = [NSString JSONString:paramsDict];
                        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"getusertype",paramsStr];
                        
                        NSData *paramsData = [result toGBKEncodingData];
                        userTypeRequest.postBody = [paramsData mutableCopy];
                        
                        [userTypeRequest startAsynchronous];
                    }
                }
            }
        }
            
            break;
            
        default:
            break;
    }
}

// 提交注册
- (IBAction)postToRegister:(id)sender {
    // 检查填写内容是否为空
    if ([NSString emptyValidate:_chooseArea_cityTxtField.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请选择省市！"];
        
        return;
    }
    if ([NSString emptyValidate:_chooseArea_countyTxtField.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请选择频道！"];
        
        return;
    }
    if ([NSString emptyValidate:_memberTypeTxtField.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请选择会员类型！"];
        
        return;
    }
    if ([NSString emptyValidate:_usernameTxtField.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请填写用户名！"];
        
        return;
    }
    if ([NSString emptyValidate:_pwdTxtField.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请填写密码！"];
        
        return;
    } else {
        
        // 密码输入限制（数字字母下划线） >6位
        // return NO to not change text
        if(strlen([_pwdTxtField.text UTF8String]) <6)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wrong password" message:@"Password can not less than 6 character" delegate:self cancelButtonTitle:@"Go on Input" otherButtonTitles:nil];
            [alert show];
            
            [_pwdTxtField becomeFirstResponder];
            
            return ;
        }
    }
    
    
    // 是否确认了密码
    if ([NSString emptyValidate:_confirmPwdTxtField.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请确认密码！"];
        
        return;
    } else {
        if (![NSString emptyValidate:_pwdTxtField.text]) {
            if (![_confirmPwdTxtField.text isEqualToString:_pwdTxtField.text]) {
                [SVProgressHUD showErrorWithStatus:@"和所填密码不符 请再次确认！"];
                return;
            }
        }
    }
    // 是否填写了邮箱
    if ([NSString emptyValidate:_emailTxtField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请填写邮箱！"];
        
        return;
    } else {
        // 检测邮箱是否有效
        if (![self emailCheck:_emailTxtField.text]) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid mail" message:@"请输入有效的邮箱！" delegate:self cancelButtonTitle:@"Go on Input" otherButtonTitles:nil];
            [alert show];
            
            [_emailTxtField becomeFirstResponder];
            
            return ;
        }
    }
//    // 检查验证码是否填写
//    if ([NSString emptyValidate:_captchaTxtField.text]) {
//        
//        [SVProgressHUD showErrorWithStatus:@"请输入验证码！"];
//        
//        return;
//    }
    
    
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        // 提示正在注册
        loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        loadHud.labelText = @"正在注册，请稍后...";
        
        /* 会员注册 */
        registerRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        registerRequest.requestMethod = @"POST";
        // 设置超时时间
        registerRequest.timeOutSeconds = 30;
        registerRequest.delegate = self;
        // 设置参数
        NSDictionary *paramsDict =  @{@"province": pid, @"city": cid, @"type": mid, @"username": _usernameTxtField.text, @"userpwd": [_pwdTxtField.text md5]};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"zhuce",paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        registerRequest.postBody = [paramsData mutableCopy];
        
        [registerRequest startAsynchronous];
    }
}


#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request{
    NSLog(@"%@",request.responseString);
    if (request == provinceRequest) {//城市(省份)
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [loadHud hide:YES];
                
                NSDictionary *info = result[@"info"];
                provinceData = info[@"data"];
                
                [provinceArr removeAllObjects];
                for (NSDictionary *dict in provinceData) {
                    NSString *province = dict[@"textvalue"];
                    
                    [provinceArr addObject:province];
                }
                
                
                // 进入选择界面
                [self enterChoiceVCWithNavTitle:@"选择省市" SelectTag:1 DataArr:provinceArr];
                
                
            } else {
                [loadHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
            
        } else {
            [loadHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    }
    if (request == cityRequest) {//频道
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [loadHud hide:YES];
                
                NSDictionary *info = result[@"info"];
                cityData = info[@"data"];
                
                [cityArr removeAllObjects];
                for (NSDictionary *dict in cityData) {
                    NSString *city = dict[@"textvalue"];
                    
                    [cityArr addObject:city];
                }
                
                
                // 进入选择界面
                [self enterChoiceVCWithNavTitle:@"选择频道" SelectTag:2 DataArr:cityArr];
                
            } else {
                [loadHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
            
        } else {
            [loadHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    }
    if (request == userTypeRequest) {//会员类型
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [loadHud hide:YES];
                
                NSDictionary *info = result[@"info"];
                userTypeData = info[@"data"];
                
                [userTypeArr removeAllObjects];
                for (NSDictionary *dict in userTypeData) {
                    NSString *userType = dict[@"textvalue"];
                    
                    [userTypeArr addObject:userType];
                }
                
                
                // 进入选择界面
                [self enterChoiceVCWithNavTitle:@"选择会员类型" SelectTag:3 DataArr:userTypeArr];
                
            } else {
                [loadHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
            
        } else {
            [loadHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    }
    if (request == registerRequest) {//会员注册
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [loadHud hide:YES];
                
                // 注册成功 进入主页...
                
                NSDictionary *info = result[@"info"];
                NSString *username = info[@"username"];
                NSString *userId = info[@"cid"];
                
                // 保存用户名和用户id
                [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
                [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"username"];
                
                YH_HomeViewController *homeVC = [[YH_HomeViewController alloc]initWithNibName:@"YH_HomeViewController" bundle:nil];
                [self.navigationController pushViewController:homeVC animated:YES];
                
                
                
//                // 进入网站风格页
//                YH_WebStyleViewController *webStyleVC = [[YH_WebStyleViewController alloc]initWithNibName:@"YH_WebStyleViewController" bundle:nil];
//                [self.navigationController pushViewController:webStyleVC animated:YES];
                
            } else {
                [loadHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
            
        } else {
            [loadHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [loadHud hide:YES];
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

#pragma mark - enterChoiceVC

- (void)enterChoiceVCWithNavTitle:(NSString*)navTitle SelectTag:(NSInteger)selectTag DataArr:(NSArray*)dataArr {
    
    ChoicesTableViewController *choicesVC = [[ChoicesTableViewController alloc]init];
    choicesVC.choiceDelegate = self;
    
    choicesVC.title = navTitle;
    choicesVC.tag_ = selectTag;
    choicesVC.dataArr = dataArr;
    [choicesVC.tableView reloadData];
    
    UINavigationController *choicesNav = [[UINavigationController alloc]initWithRootViewController:choicesVC];
    [self presentViewController:choicesNav animated:YES completion:nil];
    choicesNav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:22.0]};
    
    if (MAIN_VERSION >= 7) {
        choicesNav.navigationBar.barTintColor = APP_COLOR;
        
    } else {
        choicesNav.navigationBar.tintColor = APP_COLOR;
    }
}


#pragma mark - ShowChoiceDelegate

- (void)showChoice:(NSString*)choice SelectedIndex:(NSInteger)selectedIndex Tag:(NSInteger)tag {
    switch (tag) {
        case 1:
            _chooseArea_countyTxtField.text = nil;
            _memberTypeTxtField.text = nil;
            
            _chooseArea_cityTxtField.text = choice;
            pid = provinceData[selectedIndex][@"idvalue"];
            
            break;
        case 2:
            _memberTypeTxtField.text = nil;
            
            _chooseArea_countyTxtField.text = choice;
            cid = cityData[selectedIndex][@"idvalue"];
            
            break;
        case 3:
            
            _memberTypeTxtField.text = choice;
            mid = userTypeData[selectedIndex][@"idvalue"];
            
            break;
            
        default:
            break;
    }
}



// 返回
- (void)back {
    [provinceRequest cancel];
    [cityRequest cancel];
    [userTypeRequest cancel];
    [registerRequest cancel];
    
    self.navigationController.navigationBarHidden = YES;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end
